package com.lpf.back.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import com.aliyun.oss.OSSClient;
import com.lpf.back.common.OssConstant;
import com.lpf.back.domain.Dynamic;
import com.lpf.back.domain.User;
import com.lpf.back.mapper.DynamicMapper;
import com.lpf.back.mapper.UserMapper;
import com.lpf.back.service.interfaces.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OSSClient ossClient;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DynamicMapper dynamicMapper;

    /**
     * 上传图片到OSS服务器
     *
     * @return oss服务器图片访问url
     */
    @Override
    public User uploadPic(HttpServletRequest request, MultipartFile file) {
        String picUrl = "";
        User user = null;
        try {
            String id = request.getParameter("id");
            System.out.println(id);
            MultipartFile avatarImage = file;
//            System.out.println(avatarImage);

            //2.生成oss服务器图片名称（这里用uuid拼接一个name，防止上传图片与其他图片重名而覆盖同名oss文件）
            String fileName = "images/" + UUID.randomUUID().toString().replace("-", "") + "_" + avatarImage.getOriginalFilename();
            //3.上传到oss服务器
            picUrl = uploadToOss(fileName, new ByteArrayInputStream(avatarImage.getBytes()));
            //System.out.println(picUrl);
            user = userMapper.selectById(id);
            user.setAvatar(picUrl);
            userMapper.updateById(user);

        } catch (Exception e) {
            log.error("picture upload failed. error:", e);
        }
        System.out.println(picUrl);
        return user;
    }

    @Override
    public Dynamic dynamic(HttpServletRequest request, MultipartFile picture) {
        String picUrl = "";
        Dynamic dynamic = new Dynamic();
        String id = request.getParameter("id");
        String releaseContent = request.getParameter("releaseContent");
        String fileName = "images/" + UUID.randomUUID().toString().replace("-", "") + "_" + picture.getOriginalFilename();
        try {
            picUrl = uploadToOss(fileName, new ByteArrayInputStream(picture.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        dynamic.setId(null);
        dynamic.setLikes(0);
        dynamic.setPersonid(Integer.parseInt(id));
        dynamic.setReleaseDate(new Date(System.currentTimeMillis()));
        dynamic.setPicture(picUrl);
        dynamic.setReleaseContent(releaseContent);
        System.out.println("动态图片上传的URL：" + picUrl);
        //dynamic.setId(1);
        //dynamicMapper.updateById(dynamic);
        dynamicMapper.insert(dynamic);
        return dynamic;
    }

    @Override
    public Dynamic dynamicNoImg(String releaseContent, Integer id) {
        Dynamic dynamic = new Dynamic();
        dynamic.setId(null);
        dynamic.setLikes(0);
        dynamic.setPersonid(id);
        dynamic.setReleaseDate(new Date(System.currentTimeMillis()));
        dynamic.setPicture(null);
        dynamic.setReleaseContent(releaseContent);
        dynamicMapper.insert(dynamic);
        return dynamic;
    }

    /**
     * 上传图片
     *
     * @param fileName 图片名称，图片名称包括文件夹名称和“/”
     * @param in 图片输入流
     */
    private String uploadToOss(String fileName, InputStream in) throws Exception {
        // 上传Object.
        ossClient.putObject(OssConstant.BUCKET, fileName, in);
        //返回上传图片的url
        return "http://" + OssConstant.BUCKET + "." + OssConstant.END_POINT + "/" + fileName;
//        return ossClient.generatePresignedUrl(OssConstant.BUCKET, fileName).toString();
    }
}
